//
// Created by dlr123 on 2021/11/15.
//

#include "can_conf.h"
/**
 *
 * */
HAL_StatusTypeDef CAN_SetFilters() {

    CAN_FilterTypeDef canFilter;
    canFilter.FilterBank = 0;
    canFilter.FilterMode = CAN_FILTERMODE_IDMASK;
    canFilter.FilterScale = CAN_FILTERSCALE_32BIT;

    canFilter.FilterIdHigh = 0;
    canFilter.FilterIdLow = 0; //后四位是1100=0xC
//    canFilter.FilterMaskIdHigh = 0xF800;
//    canFilter.FilterMaskIdLow = 0x000E;
    canFilter.FilterMaskIdHigh = 0;
    canFilter.FilterMaskIdLow = 0;

    canFilter.FilterFIFOAssignment = CAN_RX_FIFO0;
    canFilter.FilterActivation = ENABLE;
    canFilter.SlaveStartFilterBank = 14;

    HAL_StatusTypeDef result = HAL_CAN_ConfigFilter(&hcan1, &canFilter);
    return result;
}


void CAN_SendMsg(uint8_t Instruct,uint8_t Index, uint8_t TxData[8], uint8_t Data_Len) {
    CAN_TxHeaderTypeDef TxHeader;
    TxHeader.ExtId = Generate_msgID(Instruct,Index);
    TxHeader.StdId = 0;
    TxHeader.RTR = CAN_RTR_DATA;
    TxHeader.IDE = CAN_ID_EXT;
    TxHeader.DLC = Data_Len;
    TxHeader.TransmitGlobalTime = DISABLE;

    while (HAL_CAN_GetTxMailboxesFreeLevel(&hcan1) < 1) {
    }
    printf("Send MsgID = 0x%08x\n", TxHeader.ExtId);
    uint32_t TxMailbox;
    if (HAL_CAN_AddTxMessage(&hcan1, &TxHeader, TxData, &TxMailbox) != HAL_OK) {
        printf("Send to mailbox error!\n");
    }
}

void CAN_ReadMsg(uint32_t FIFO_num) {
    CAN_RxHeaderTypeDef RxHeader;
    uint8_t RxData[8];
    if (FIFO_num == CAN_RX_FIFO0) {
        printf("Msg received by FIFO0\n");
        if (HAL_CAN_GetRxMessage(&hcan1, CAN_RX_FIFO0, &RxHeader, RxData) !=
            HAL_OK) {
            printf("Read FIFO0 error\n");
            return;
        }
        printf("ExdID = %08x\n", RxHeader.ExtId);
        printf("RTR(0=Data,2=Remote) = %d\n", RxHeader.RTR);
        printf("IDE(0=Std,4=Ext) = %d\n", RxHeader.IDE);
//        printf("FilterMatchIndex = %d\n", RxHeader.FilterMatchIndex);
        printf("DLC(Data length) = %d\n", RxHeader.DLC);
        printf("Rx_Uart_Data = ");
        for (uint8_t i = 0; i < RxHeader.DLC; i++) {
            printf("%02x ",RxData[i]);
        }
        printf("\n----------------------------------\n");
    }
}

void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan1) {
    CAN_ReadMsg(CAN_RX_FIFO0);
}
